﻿using System;
using System.Reflection;

namespace ValidationHelper.Validators
{
    public abstract class Validator
    {
        #region Propriedades
        public Type ExceptionType { get; set; }
        public string Message { get; private set; }
        #endregion

        #region Constantes
        private static readonly Type StringType = Type.GetType("System.String");
        private static readonly Type SystemExceptionType = Type.GetType("System.Exception");
        #endregion

        #region Construtores
        public Validator(string message, Type exceptionType)
        {
            Message = message;
            ExceptionType = exceptionType;
        }
        #endregion

        #region Métodos
        public void Validate()
        {
            if (IsNotValid())
            {
                ThrowException();
            }
        }

        private void ThrowException()
        {
            if (IsValidException())
            {
                throw (Exception)ExceptionType.GetConstructor(new Type[] { StringType }).Invoke(new object[] { Message });
            }
            else
            {
                throw new ValidationHelperException(Message);
            }
        }

        private bool IsValidException()
        {
            if (ExceptionType == null || !(ExceptionType.IsSubclassOf(SystemExceptionType)))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        protected abstract bool IsNotValid();
        #endregion
    }
}
